<template>
  <div class="confirmOrder-container">
    <Headbar />
    <HeadCartBrand title="确认订单" />
    <div class="confirm-order-wrap">
      <div class="panel-title">
        <h4>收货人信息</h4>
        <a href="javascript:;" @click="handleShowDialogAddress()" v-if="addressList.length"><img src="@/assets/images/cart/icon-address-add.png" />新增收货信息</a>
      </div>
      <div class="panel-address-list" v-if="!addressList.length">
        <div class="add-address" @click="handleShowDialogAddress()">
          <img src="@/assets/images/cart/icon-address-add.png" />新增收货信息
        </div>
      </div>
      <div class="panel-address-list" v-if="addressList.length">
        <a href="javascript:;" class="btn" @click="handleScrollPage('prev')">
          <img src="@/assets/images/cart/btn-prev-disabled.png" v-if="scrollPage==0" />
          <img src="@/assets/images/cart/btn-prev.png" v-if="scrollPage>0 && scrollPage<scrollMaxPage" />
        </a>
        <div class="address-scroll-wrap">
          <ul :style="{ 'margin-left': scrollWidth }">
            <li class="item" :class="{'active' : addressActive == index}" v-for="(item, index) in addressList" @click="handleSelectAddress(index)">
              <div class="title">
                <strong>{{ item.consignee }}</strong>
                <b>{{ item.phone }}</b>
                <span v-if="item.isDefault == 1">默认</span>
                <a href="javascript:;" @click="handleShowDialogAddress(index)">编辑</a>
              </div>
              <div class="info">
                <p>{{ item.provinceName }} {{ item.cityName }} {{ item.districtName }}</p>
                <p class="add-info">{{ item.address }}</p>
              </div>

              <img src="@/assets/images/cart/icon-checked-arrow.png" class="icon" />

            </li>
          </ul>
        </div>
        <a href="javascript:;" class="btn" @click="handleScrollPage('next')">
          <img src="@/assets/images/cart/btn-next-disabled.png" v-if="scrollPage==scrollMaxPage-1" />
          <img src="@/assets/images/cart/btn-next.png" v-if="scrollPage>=0 && scrollPage<scrollMaxPage-1" />
        </a>
      </div>
      <div class="panel-title">
        <h4>商品清单</h4>
      </div>

      <div class="confirm-order-list" v-for="(item, index) in orderList">
        <div class="hd">{{ item.factoryName }}</div>
        <ul class="bd">
          <li>
            <div class="product-info">
              <div class="item-info" v-for="(panel, i) in item.cartItemDTOList">
                <div class="pic">
                  <img :src="URL.PIC + panel.productPic" />
                </div>
                <div class="info">
                  <div class="title">{{ panel.productName }}</div>
                  <div class="specifications">{{ panel.productSpec }}</div>
                </div>
                <div class="price">¥ {{ panel.productPrice }}</div>
                <div class="num">X{{ panel.quantity }}</div>
              </div>
              <div class="msg">留言<input type="text" v-model="item.memo" maxlength="50" /></div>
            </div>
            <div class="product-invoice">
              <div class="invoice-title">配送<!-- <span>¥ 100</span> --></div>
              <div class="invoice-item">
                <div class="item" :class="{'active': k == item.transportIndex }" v-for="(n, k) in item.transport" @click="handleTransport(k, index)">{{ n }}<img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></div>
              </div>
              <div class="invoice-title">发票</div>
              <div class="invoice-item">
                <div class="item active"><span v-html="item.invoiceInfo"><i></i></span><img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></div>
                <a href="javascript:;" @click="handleEditInvoice(index)">修改</a>
              </div>
            </div>
          </li>
        </ul>
      </div>

      <div class="confirm-info">
        <p><span>商品总金额： </span><strong>￥{{ amountInfo.productAmount }}</strong></p>
        <p><span>总运费：</span><strong>￥{{ amountInfo.freight }}</strong></p>
        <!-- <p><span>优惠金额： </span><strong>￥0.00</strong></p> -->
        <p class="total"><span>应付合计：</span><strong>￥{{ amountInfo.orderAmount }}</strong></p>
      </div>

      <div class="confirm-submit">
        <div class="user-info">
          <div class="info">寄送至：<span>{{ addressInfo.consignee }}</span>{{ addressInfo.phone }}</div>
          <p>{{ addressInfo.provinceName }}{{ addressInfo.cityName }}{{ addressInfo.districtName }}{{ addressInfo.address }}</p>
        </div>
        <a href="javascript:;" class="btn" @click="handleConfirm()">提交订单</a>
      </div>

    </div>
    <Footbars />


    <!--新增地址-->
    <el-dialog :title="title" :visible.sync="dialogAddress" custom-class="form-dialog-address" width="600px" @close="dialogAddressClose()">
      <el-form :model="formAddress" :rules="rules" ref="formAddress" label-width="130px">
        <el-form-item label="姓名" prop="consignee">
          <el-input v-model="formAddress.consignee" placeholder="请输入收货人姓名" maxlength="25"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formAddress.phone" placeholder="请输入收货人手机号码" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="provinceId">
          <SelectArea ref="children" class="no-ver" @changeArea="changeArea" :area="area" />
          <!-- <el-input v-model="formAddress.districtId" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formAddress.address" placeholder="如道路、门牌号、楼栋号" maxlength="50"></el-input>
        </el-form-item>
        <el-checkbox v-model="isDefault" class="checkbox">设为默认地址</el-checkbox>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddress = false">取 消</el-button>
        <el-button type="primary" @click="handleSave()">保 存</el-button>
      </div>
    </el-dialog>

    <!--订单异常-->
    <el-dialog
      title="提示"
      :visible.sync="dialogAbnormal"
      width="680px">
      <div class="pro-abnormal">
        <div class="title">抱歉，您本单购买的商品状态已变更，请重新选择</div>
        <div class="list">
          <div class="item" v-for="(item, index) in abnormalList">
            <img :src="URL.PIC + item.productPic" />
            <div class="info">
              <div class="name">
                <p>{{ item.productName }}</p>
                <!-- <span>{{ item.productName }}</span> -->
              </div>
              <div class="price">￥{{ item.productPrice }}<!-- <span>库存不足，请重选</span> --></div>
              <div class="num">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleBack()">返回进货车</el-button>
        <el-button type="primary" @click="handleRemove()">本单中移除商品</el-button>
      </span>
    </el-dialog>

    <!--发票信息选择-->
    <el-dialog title="发票信息" :visible.sync="dialogInvoiceInfo" custom-class="form-dialog-invoice" width="780px" @close="dialogInvoiceInfoClose()">
      <div class="invoice-info">
        <div class="info-title">发票类型<p>该类型发票信息若从未填写过，则进入页面显示如下：</p></div>
        <div class="info-list">
          <span :class="{'active': invoiceTypeIndex == i}" v-for="(item, i) in invoiceType" @click="handleChangeInvoiceType(i)">{{ item }}<img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></span>
        </div>
        <!--不开发票-->
        <div v-if="invoiceShowListTag != 4">
          <div class="info-title">发票信息<a href="javascript:;" @click="handleShowDialogInvoice()"><img src="@/assets/images/cart/icon-address-add.png" />新增发票信息</a></div>
          <!--增值税发票-->
          <div v-if="invoiceShowListTag != 3">
            <div class="info-list">
              <span :class="{'active': invoiceInfoIndex == i}" v-for="(item, i) in invoiceInfo" @click="handleChangeInvoiceInfo(i)">{{ item }}<img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></span>
            </div>
          </div>
          <!--个人-->
          <div class="invoice-list" v-if="invoiceShowListTag == 1">
            <div class="invoice-scroll" v-if="invoicePeople.length">
              <div class="btn btn-prev" :class="{'disabled': scrollIndex == 0}" @click="handleScroll('prev')"></div>
              <div class="scroll-box">
                <div class="box" :style="{ 'margin-left': scrollW }">
                  <div class="item" :class="{'active': invoicePeopleIndex == i}" v-for="(item, i) in invoicePeople" @click="handleChangeInvoicePeople(i)">发票抬头：{{ item.title }}<img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></div>
                </div>
              </div>
              <div class="btn btn-next" :class="{'disabled': scrollIndex == invoicePeople.length-3}" @click="handleScroll('next')"></div>
            </div>
            <div class="info-empty" v-else>暂无发票信息，<a href="javascript:;" @click="handleShowDialogInvoice()">去添加~</a></div>
          </div>

          <!--单位-->
          <div class="invoice-list" v-if="invoiceShowListTag == 2">
            <div class="invoice-scroll unit" v-if="invoiceUnit.length">
              <div class="btn btn-prev" :class="{'disabled': scrollIndex == 0}" @click="handleScroll('prev')"></div>
              <div class="scroll-box">
                <div class="box" :style="{ 'margin-left': scrollW }">
                  <div class="item" :class="{'active': invoiceUnitIndex == i}" v-for="(item, i) in invoiceUnit" @click="handleChangeInvoiceUnit(i)">
                    <p><span>发票抬头：</span>{{ item.title }}</p>
                    <p><span>纳税人识别号：</span>{{ item.taxPayerCode }}</p>
                    <img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" />
                  </div>
                </div>
              </div>
              <div class="btn btn-next" :class="{'disabled': scrollIndex == invoiceUnit.length-2}" @click="handleScroll('next')"></div>
            </div>
            <div class="info-empty" v-else>暂无发票信息，<a href="javascript:;" @click="handleShowDialogInvoice()">去添加~</a></div>
          </div>

          <!--增值税-->
          <div class="invoice-list" v-if="invoiceShowListTag == 3">
            <div class="invoice-scroll vat" v-if="invoiceVat.length">
              <div class="btn btn-prev" :class="{'disabled': scrollIndex == 0}" @click="handleScroll('prev')"></div>
              <div class="scroll-box">
                <div class="box" :style="{ 'margin-left': scrollW }">
                  <div class="item" :class="{'active': invoiceVatIndex == i}" v-for="(item, i) in invoiceVat" @click="handleChangeInvoiceVat(i)">
                    <p><span>发票抬头：</span>{{ item.title }}</p>
                    <p><span>纳税人识别号：</span>{{ item.taxPayerCode }}</p>
                    <p><span>注册地址：</span>{{ item.title }}</p>
                    <p><span>注册电话：</span>{{ item.taxPayerCode }}</p>
                    <p><span>开户银行：</span>{{ item.title }}</p>
                    <p><span>银行账户：</span>{{ item.taxPayerCode }}</p>
                    <img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" />
                  </div>
                </div>
              </div>
              <div class="btn btn-next" :class="{'disabled': scrollIndex == invoiceVat.length-2}" @click="handleScroll('next')"></div>
            </div>
            <div class="info-empty vat-empty" v-else>暂无发票信息，<a href="javascript:;" @click="handleShowDialogInvoice()">去添加~</a></div>
          </div>

          <div class="info-title">发票内容</div>
          <div class="info-list">
            <span :class="{'active': invoiceContIndex == i}" v-for="(item, i) in invoiceCont" @click="handleChangeInvoiceCont(i)">{{ item }}<img src="@/assets/images/cart/icon-checked-arrow-small.png" class="icon" /></span>
          </div>

        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInvoiceInfo = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveInvoiceInfo()">确 定</el-button>
      </div>
    </el-dialog>

    <!--发票信息添加-->
    <el-dialog title="发票信息添加" :visible.sync="dialogInvoice" custom-class="form-dialog-invoice" width="660px" @close="dialogInvoiceClose()">
      <el-form :model="formInvoice" :rules="rulesInvoice" ref="formInvoice" label-width="130px">
        <el-form-item label="发票抬头" prop="title">
          <el-input v-model="formInvoice.title" placeholder="请输入发票抬头" maxlength="50"></el-input>
        </el-form-item>
         <el-form-item label="纳税人识别号" prop="taxPayerCode" v-if="invoiceShowListTag == 2 || invoiceShowListTag == 3">
          <el-input v-model="formInvoice.taxPayerCode" placeholder="请输入纳税人识别号"></el-input>
        </el-form-item>
        <el-form-item label="注册地址" prop="companyAddress" v-if="invoiceShowListTag == 3">
          <el-input v-model="formInvoice.companyAddress" placeholder="请输入注册地址" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="注册电话" prop="telephone" v-if="invoiceShowListTag == 3">
          <el-input v-model="formInvoice.telephone" placeholder="请输入注册电话" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName" v-if="invoiceShowListTag == 3">
          <el-input v-model="formInvoice.bankName" placeholder="请输入开户银行" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="银行账户" prop="backAccount" v-if="invoiceShowListTag == 3">
          <el-input v-model="formInvoice.backAccount" placeholder="请输入银行账户" maxlength="30"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInvoice = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveInvoice()">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Headbar from '@/components/Layouts/Headbar'
import HeadCartBrand from '@/components/Layouts/HeadCartBrand'
import Footbars from '@/components/Layouts/Footbars'
import SelectArea from '@/components/SelectArea'
import { getBalanceList, getSettleAmount, createOrder, getSelectProduct } from '@/api/cart'
import { getAddressList, addAddress, updateAddress } from '@/api/member'
import { addInvoice, getInvoice } from '@/api/invoice'

export default {
  name: 'ConfirmOrder',
  components: {
    Headbar,
    HeadCartBrand,
    Footbars,
    SelectArea
  },
  data() {
    const checkMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else {
        if(!/^1\d{10}$/.test(value)){
          callback(new Error('请输入11位手机号码'))
        }else{
          callback();
        }
      }
    }

    const checkIdentification = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入纳税人识别号'))
      } else {
        if(!/^[a-zA-Z\d]{15,18}$/.test(value)){
          callback(new Error('纳税人识别号限制15~18字符内，可使用数字、字母'))
        }else{
          callback();
        }
      }
    }

    return {
      abnormalList: [],
      dialogAbnormal: false,
      dialogAddress: false,
      isDefault: false,
      formAddress: {
        consignee: "",
        phone: "",
        address: "",
        zipCode: "1",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        districtId: "",
        districtName: ""
      },
      editAddressInfo: '', //编辑地址信息
      area: [],
      rules: {
        consignee: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkMobile, trigger: 'blur' }
        ],
        // provinceId: [
        //   { required: true, message: '请选择所在地区', trigger: 'blur' }
        // ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
      },
      addressActive: 0, //默认选中第一个地址
      addressList: [], //收货地址列表
      addressInfo: {}, //选中收货地址
      orderList: [], //确认订单列表
      amountInfo: {}, //结算信息
      scrollPage: 0,
      scrollMaxPage: 0,
      scrollWidth: 0,
      title:'新增收货信息',
      productSpecificationId: this.getUrlParams('productSpecificationId'),
      quantity: this.getUrlParams('quantity'),
      formInvoice: {
        title: '',
        invoiceType: 3,
        taxPayerCode: '',
        companyAddress: '',
        telephone: '',
        bankName: '',
        backAccount: ''
      },
      rulesInvoice: {
        title: [
          { required: true, message: '请输入发票抬头', trigger: 'blur' }
        ],
        taxPayerCode: [
          { required: true, validator: checkIdentification, trigger: 'blur' }
        ],
        companyAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入注册电话', trigger: 'blur' }
        ],
        bankName: [
          { required: true, message: '请输入开户银行', trigger: 'blur' }
        ],
        backAccount: [
          { required: true, message: '请输入银行账户', trigger: 'blur' }
        ],
      },
      dialogInvoice: false,
      dialogInvoiceInfo: false,
      invoicePeople: [], //普通个人发票列表
      invoicePeopleIndex: 0, //普通个人发票列表默认选中第一个
      invoiceUnit: [], //普通单位发票列表
      invoiceUnitIndex: 0, //普通单位发票列表默认选中第一个
      invoiceVat: [], //增值税专用发票列表
      invoiceVatIndex: 0, //增值税专用发票列表默认选中第一个
      invoiceType: ['普通发票','增值税专用发票','不开发票'], //发票类型
      invoiceTypeIndex: 2, //发票类型默认选中第一个
      invoiceInfo: ['个人','单位'], //发票信息
      invoiceInfoIndex: 0, //发票信息默认选中第一个
      invoiceCont: ['商品明细','商品类别'], //发票内容
      invoiceContIndex: 0, //发票内容默认选中第一个
      invoiceShowListTag: 4, //1=>个人，2=>单位，3=>增值税，4=>不开发票
      invoiceEditIndex: 0, //修改当前发票索引
      scrollIndex: 0, //发票滚动索引
      scrollW: 0//发票滚动长度
    }
  },
  created() {
    this.getAddressList();
    this.getBalanceList();
    this.getInvoice();
    if(this.productSpecificationId!='' && this.quantity!=''){
      this.getSelectProduct();
    }
  },
  methods: {
    //修改当前发票索引
    handleEditInvoice(index) {
      this.dialogInvoiceInfo = true
      this.invoiceEditIndex = index

      this.invoiceTypeIndex = this.orderList[index].invoiceTypeIndex
      this.invoiceInfoIndex = this.orderList[index].invoiceInfoIndex
      this.invoiceContIndex = this.orderList[index].invoiceContIndex

      this.scrollIndex = 0
      this.scrollW = 0

      const invoiceTemplateId = this.orderList[index].invoiceTemplateId

      if(this.invoiceTypeIndex == 0){ //普通发票
        if(this.invoiceInfoIndex == 0){ //个人

          const checkedInvoiceIndex = this.getCheckInvoiceIndex(invoiceTemplateId, this.invoicePeople)
          if(checkedInvoiceIndex == -1){
            this.invoicePeopleIndex = 0
          }else{
            this.invoicePeopleIndex = checkedInvoiceIndex
          }
          this.scrollIndex = checkedInvoiceIndex
          if(this.scrollIndex>this.invoicePeople.length-3){
            this.scrollIndex = this.invoicePeople.length-3
          }
          this.scrollW = - this.scrollIndex * 215 +'px'

        }else{ //单位
          const checkedInvoiceIndex = this.getCheckInvoiceIndex(invoiceTemplateId, this.invoiceUnit)
          if(checkedInvoiceIndex == -1){
            this.invoiceUnitIndex = 0
          }else{
            this.invoiceUnitIndex = checkedInvoiceIndex
          }
          this.scrollIndex = checkedInvoiceIndex
          if(this.scrollIndex>this.invoiceUnit.length-2){
            this.scrollIndex = this.invoiceUnit.length-2
          }
          this.scrollW = - this.scrollIndex * 322 +'px'
        }
      }else if(this.invoiceTypeIndex == 1){ //增值税专用发票
        const checkedInvoiceIndex = this.getCheckInvoiceIndex(invoiceTemplateId, this.invoiceVat)
        if(checkedInvoiceIndex == -1){
          this.invoiceVatIndex = 0
        }else{
          this.invoiceVatIndex = checkedInvoiceIndex
        }
        this.scrollIndex = checkedInvoiceIndex
        if(this.scrollIndex>this.invoiceVat.length-2){
          this.scrollIndex = this.invoiceVat.length-2
        }
        this.scrollW = - this.scrollIndex * 322 +'px'
      }else{ //不开发票

      }

      this.invoiceMatchingData()

      console.log(this.scrollW)
    },
    //切换发票类型
    handleChangeInvoiceType(index) {
      if(index == 0 && this.orderList[this.invoiceEditIndex].isGeneralInvoice == 0){
        this.$message({
          type: 'error',
          message: '商家不支持开具普通发票'
        });
        return
      }
      if(index == 1 && this.orderList[this.invoiceEditIndex].isSpecialInvoice == 0){
        this.$message({
          type: 'error',
          message: '商家不支持开具增值税专用发票'
        });
        return
      }
      this.scrollW = 0;
      this.scrollIndex = 0;
      this.invoiceVatIndex = 0;
      this.invoiceTypeIndex = index;
      this.invoiceMatchingData();
    },
    //切换发票信息
    handleChangeInvoiceInfo(index) {
      this.scrollW = 0;
      this.scrollIndex = 0;
      this.invoicePeopleIndex = 0;
      this.invoiceUnitIndex = 0;
      this.invoiceInfoIndex = index
      this.invoiceMatchingData()
    },
    //切换发票内容
    handleChangeInvoiceCont(index) {
      this.invoiceContIndex = index
      this.invoiceMatchingData()
    },
    //切换普通发票-个人
    handleChangeInvoicePeople(index) {
      this.invoicePeopleIndex = index
    },
    //切换普通发票-单位
    handleChangeInvoiceUnit(index) {
      this.invoiceUnitIndex = index
    },
    //切换增值税发票
    handleChangeInvoiceVat(index) {
      this.invoiceVatIndex = index
    },
    //保存添加发票
    handleSaveInvoice() {
      this.$refs.formInvoice.validate((valid) => {
        if (valid) {
          this.invoicePeople = [];
          this.invoiceUnit = [];
          this.invoiceVat = [];
          this.addInvoice();
        } else {
          return false;
        }
      });
    },
    handleShowDialogInvoice() {
      if(this.invoiceShowListTag == 1 && this.invoicePeople.length>=5 || this.invoiceShowListTag == 2 && this.invoiceUnit.length>=5 || this.invoiceShowListTag == 3 && this.invoiceVat.length>=5){
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          customClass: 'sales-msgbox',
          message: h('p', null, [
            h('span', null, '新增发票信息已达上限，可在'),
            h('span', { style: 'color: #409EFF' }, '发票设置'),
            h('span', '管理您的发票信息')
          ]),
          showCancelButton: true,
          confirmButtonText: '去设置',
          cancelButtonText: '取消'
        }).then(() => {
          this.routeToPath('/member/setup/invoice');
          console.log('go to setting')
        }).catch(() => {

        });

        return
      }

      this.dialogInvoice = true
    },
    //发票滚动切换
    handleScroll(dir) {
      if(this.invoiceShowListTag == 1){ //普通个人
        if(dir == 'prev'){
          this.scrollIndex--
          if(this.scrollIndex<=-1){
            this.scrollIndex = 0
            return
          }
          this.scrollW = - this.scrollIndex * 215 +'px'
        }else{
          this.scrollIndex++
          if(this.scrollIndex>this.invoicePeople.length-3){
            this.scrollIndex = this.invoicePeople.length-3
            return
          }
          this.scrollW = - this.scrollIndex * 215 +'px'
        }
      }else if(this.invoiceShowListTag == 2){ //普通单位
        if(dir == 'prev'){
          this.scrollIndex--
          if(this.scrollIndex<=-1){
            this.scrollIndex = 0
            return
          }
          this.scrollW = - this.scrollIndex * 322 +'px'
        }else{
          this.scrollIndex++
          if(this.scrollIndex>this.invoiceUnit.length-2){
            this.scrollIndex = this.invoiceUnit.length-2
            return
          }
          this.scrollW = - this.scrollIndex * 322 +'px'
        }
      }else if(this.invoiceShowListTag == 3){
        if(dir == 'prev'){
          this.scrollIndex--
          if(this.scrollIndex<=-1){
            this.scrollIndex = 0
            return
          }
          this.scrollW = - this.scrollIndex * 322 +'px'
        }else{
          this.scrollIndex++
          if(this.scrollIndex>this.invoiceVat.length-2){
            this.scrollIndex = this.invoiceVat.length-2
            return
          }
          console.log(this.scrollIndex)
          this.scrollW = - this.scrollIndex * 322 +'px'
        }
      }
    },
    //保存选择发票信息
    handleSaveInvoiceInfo() {

      this.getInvoiceCheckedInfo()

      console.log(this.getParamsList())

      console.log(this.orderList)
    },
    //获取选中发票信息索引
    getCheckInvoiceIndex(invoiceTemplateId, invoiceList) {
      if(!invoiceList.length){
        return
      }
      return invoiceList.findIndex((value)=> value.id == invoiceTemplateId)
    },
    //获取发票选中的信息
    getInvoiceCheckedInfo() {

      let invoiceInfo = ''
      let taxContent = ''
      let invoiceTemplateId = ''
      if(this.invoiceTypeIndex == 0){
        if(this.invoiceInfoIndex == 0){
          if(!this.invoicePeople.length){
            this.$message({
              type: 'error',
              message: '请添加个人发票信息'
            });
            return
          }
          invoiceInfo = this.invoiceType[this.invoiceTypeIndex]+'<i class="i-space"></i>'+this.invoiceInfo[this.invoiceInfoIndex]+'<i class="i-space"></i>'+this.invoiceCont[this.invoiceContIndex]
          invoiceTemplateId = this.invoicePeople[this.invoicePeopleIndex].id
        }else{
          if(!this.invoiceUnit.length){
            this.$message({
              type: 'error',
              message: '请添加单位发票信息'
            });
            return
          }
          invoiceInfo = this.invoiceType[this.invoiceTypeIndex]+'<i class="i-space"></i>'+this.invoiceInfo[this.invoiceInfoIndex]+'<i class="i-space"></i>'+this.invoiceCont[this.invoiceContIndex]
          invoiceTemplateId = this.invoiceUnit[this.invoiceUnitIndex].id
        }
        taxContent = this.invoiceCont[this.invoiceContIndex]
      }else if(this.invoiceTypeIndex == 1){
        console.log(this.invoiceType.length)
        if(!this.invoiceVat.length){
          this.$message({
            type: 'error',
            message: '请添加增值税专用发票信息'
          });
          return
        }
        invoiceInfo = this.invoiceType[this.invoiceTypeIndex]+'<i class="i-space"></i>'+this.invoiceCont[this.invoiceContIndex]
        invoiceTemplateId = this.invoiceVat[this.invoiceVatIndex].id
        taxContent = this.invoiceCont[this.invoiceContIndex]
      }else if(this.invoiceTypeIndex == 2){
        invoiceInfo = this.invoiceType[this.invoiceTypeIndex]
        taxContent = ''
        invoiceTemplateId = ''
      }

      this.orderList[this.invoiceEditIndex].invoiceInfo = invoiceInfo
      this.orderList[this.invoiceEditIndex].taxContent = taxContent
      this.orderList[this.invoiceEditIndex].invoiceTemplateId = invoiceTemplateId
      this.orderList[this.invoiceEditIndex].invoiceTypeIndex = this.invoiceTypeIndex
      this.orderList[this.invoiceEditIndex].invoiceInfoIndex = this.invoiceInfoIndex
      this.orderList[this.invoiceEditIndex].invoiceContIndex = this.invoiceContIndex

      this.dialogInvoiceInfo = false
    },
    //关闭添加发票前回调
    dialogInvoiceClose() {
      this.formInvoice = {
        title: '',
        invoiceType: 3,
        taxPayerCode: '',
        companyAddress: '',
        telephone: '',
        bankName: '',
        backAccount: ''
      }
    },
    //关闭发票信息前回调
    dialogInvoiceInfoClose(){

    },
    //切换发票类型显示对应的发票列表数据
    invoiceMatchingData() {
      this.invoiceCont = ['商品明细','商品类别']
      // this.scrollIndex = 0
      // this.scrollW = 0
      if(this.invoiceTypeIndex == 0){ //普通发票
        if(this.invoiceInfoIndex == 0){ //个人
          this.invoiceShowListTag = 1
        }else{ //单位
          this.invoiceShowListTag = 2
        }
      }else if(this.invoiceTypeIndex == 1){ //增值税专用发票
        this.invoiceShowListTag = 3
        this.invoiceCont = ['商品明细']
        this.invoiceContIndex = 0
      }else{ //不开发票
        this.invoiceShowListTag = 4
      }
    },
    //添加发票
    addInvoice() {
      if(this.invoiceShowListTag == 1){
        this.formInvoice = {
          title: this.formInvoice.title,
          invoiceType: this.invoiceShowListTag
        }
      }else if(this.invoiceShowListTag == 2){
        this.formInvoice = {
          title: this.formInvoice.title,
          invoiceType: this.invoiceShowListTag,
          taxPayerCode: this.formInvoice.taxPayerCode
        }
      }
      this.formInvoice.invoiceType = this.invoiceShowListTag;
      addInvoice(this.formInvoice).then(res => {
        this.$message({
          type: 'success',
          message: res.msg
        });
        this.dialogInvoice = false;
        this.getInvoice();
      }).catch(error => {
        this.$message({
          type: 'error',
          message: error.response.data.msg
        });
        this.getInvoice();
      })
    },
    //获取发票
    getInvoice() {
      getInvoice().then(res => {
        if(!res.data.length) return;
        res.data.forEach(item => {
          if(item.invoiceType == 1){
            this.invoicePeople.push(item);
          }else if(item.invoiceType == 2){
            this.invoiceUnit.push(item);
          }else if(item.invoiceType == 3){
            this.invoiceVat.push(item);
          }
        })
      })
    },
    //配送
    handleTransport(n, index) {
      if(n == 1 && this.orderList[index].isSelfPick == 0){
        this.$message({
          type: 'error',
          message: '商家不支持上门自提'
        });
        return
      }
      this.orderList[index].transportIndex = n;
      console.log(this.getParamsList())
    },
    //获取购物车列表
    getAddressList() {
      getAddressList().then(res => {
        if(res.code == 200){
          this.addressList = res.data;
          if(res.data.length){
            this.addressInfo = res.data[this.addressActive]
            this.scrollMaxPage = Math.ceil(res.data.length/3) //向上取整地址滚动的页数
          }
        }
      })
    },
    //根据购物车IDS查询商品列表
    getBalanceList() {
      const ids = this.$route.query.ids;
      if(ids == '' || ids == null || ids == undefined){
        return;
      }
      const query = {
        ids: ids
      }

      getBalanceList(query).then(res => {
        if(res.code == 200){

          res.data.forEach((item, i) => {
            item.memo = '', //留言
            item.transport = ['快递运输','上门自提'], //配送方式
            item.transportIndex = 0,    //选中的配送方式索引
            item.invoiceInfo = '不开发票', //发票信息（显示文字）
            item.invoiceTemplateId = '', //发票id
            item.taxContent = '', //发票内容
            item.invoiceTypeIndex = 2, //默认选中不开发票索引
            item.invoiceInfoIndex = 0, //默认选中个人
            item.invoiceContIndex = 0 //默认商品明细
          })
          this.orderList = res.data
          this.getSettleAmount()
          console.log(this.orderList)
        }
      })
    },
    //根据产品规格ID查询商品列表（立即购买）
    getSelectProduct() {
      const params = {
        productSpecificationId: this.productSpecificationId,
        quantity: this.quantity
      }
      getSelectProduct(params).then(res => {
        if(res.code == 200){
          res.data.forEach((item, i) => {
            item.memo = '', //留言
            item.transport = ['快递运输','上门自提'], //配送方式
            item.transportIndex = 0,    //选中的配送方式索引
            item.invoiceInfo = '不开发票', //发票信息（显示文字）
            item.invoiceTemplateId = '', //发票id
            item.taxContent = '', //发票内容
            item.invoiceTypeIndex = 2, //默认选中不开发票索引
            item.invoiceInfoIndex = 0, //默认选中个人
            item.invoiceContIndex = 0 //默认商品明细
          })
          this.orderList = res.data;
          this.getSettleAmount()
        }
      })
    },
    //创建订单
    createOrder() {
      const params = this.getParamsList();
      console.log(params)

      createOrder(params).then(res => {
        if(res.code == 200){
          if(res.data.orderNo!=''){
            // this.$router.push({
            //   name: 'MealCashierOrder',
            //   query: {
            //     productOrderNo: res.data.orderNo
            //   }
            // })
            location.href = this.URL.mall+'/meal/cashierOrder?productOrderNo='+res.data.orderNo+''
          }else{//异常商品
            this.dialogAbnormal = true;
            this.abnormalList = res.data.orderSpecificationDTOList;
          }

        }else if(res.code == 500){
          this.$message({
            type: 'error',
            message: '服务异常'
          });
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //获取结算参数
    getParamsList() {
      let postParams = {
        memberAddressId: this.addressInfo !=null ? this.addressInfo.id : '',  //会员地址ID
        provinceId: this.addressInfo !=null ? this.addressInfo.provinceId : '',  //省份ID
        payType: '1', //支付类型 1：微信 2：支付宝
        source: '5' //PC订单
      }
      let settleCartQueryList = []
      this.orderList.forEach((item, i) => {
        let settleProductQueryList = []
        item.cartItemDTOList.forEach((panel, j) => {
          settleProductQueryList.push({
            productSpecificationId: panel.productSpecificationId,
            quantity: panel.quantity,
            cartId: panel.id
          })
        })
        settleCartQueryList.push({
          factoryId: item.factoryId,
          factoryName: item.factoryName,
          transportType: parseInt(item.transportIndex)+1,
          invoiceTemplateId: item.invoiceTemplateId,
          memo: item.memo !='' ? item.memo : '',
          settleProductQueryList: settleProductQueryList,
          taxContent: item.taxContent
        })


      })
      postParams.settleCartQueryList = settleCartQueryList;
      return postParams
    },
    //获取结算金额
    getSettleAmount(){

     const params = this.getParamsList();

      getSettleAmount(params).then(res => {
        if(res.code == 200){
          this.amountInfo = res.data;
        }
      })
    },
    //点击结算
    handleConfirm() {
      if(this.addressInfo.consignee == null){
        this.$message({
          type: 'error',
          message: '收货地址不能为空'
        });
        return;
      }
      console.log(this.getParamsList())
      this.createOrder()
    },
    //显示地址弹窗
    handleShowDialogAddress(index) {
      if(index!=undefined){
        this.title = '修改收货信息'
        this.editAddressInfo = this.addressList[index];
        this.isDefault = this.addressList[index].isDefault == 1 ?  true : false;
        for(let i in this.editAddressInfo){
          this.formAddress[i] = this.editAddressInfo[i]
        }
        let provinceId = this.editAddressInfo.provinceId
        let provinceName = this.editAddressInfo.provinceName
        let cityId = this.editAddressInfo.cityId
        let cityName = this.editAddressInfo.cityName
        let districtId = this.editAddressInfo.districtId
        let districtName = this.editAddressInfo.districtName
        this.$nextTick(() => {
          this.area = [
            {
              [provinceId] : provinceName
            },
            {
              [cityId] : cityName
            },
            {
              [districtId] : districtName
            }
          ]
          console.log(this.area)
        });
      }else{
        this.title = '新增收货信息'
      }
      this.dialogAddress = true;
    },
    //保存地址
    addAddress() {

      const params = this.formAddress;
      params.isDefault = this.isDefault ? 1 : 0;
      addAddress(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getAddressList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
        this.dialogAddress = false;
      })
    },
    //修改地址
    updateAddress() {
      const params = this.formAddress;
      params.isDefault = this.isDefault ? 1 : 0;
      params.id = this.editAddressInfo.id;
      updateAddress(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getAddressList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
        this.dialogAddress = false;
      })
    },
    //获取地区
    changeArea(val) {
      let result = []
      if(val.length){
        val.forEach((item, i) => {
          for(let i in item){
            result.push({
              key: i,
              value: item[i]
            })
          }
        })
      };
      this.formAddress.provinceId = result[0].key,
      this.formAddress.provinceName = result[0].value,
      this.formAddress.cityId = result[1].key,
      this.formAddress.cityName = result[1].value,
      this.formAddress.districtId = result[2].key,
      this.formAddress.districtName = result[2].value
    },
    //关闭地址弹出层
    dialogAddressClose() {
      this.isDefault = false;
      this.formAddress.consignee = ""
      this.formAddress.phone = ""
      this.formAddress.address = ""
      this.formAddress.zipCode = ""

      this.$nextTick(() => {
        this.area = []
      });
     // this.formAddress.consignee = ''
     // this.formAddress.phone = ''
     // this.formAddress.address = ''
    },
    //保存
    handleSave() {

      this.$refs.formAddress.validate((valid) => {
        if (valid) {
          if(this.formAddress.provinceId == ''){
            this.$message({
              type: 'error',
              message: '请选择所在地区'
            });
            return;
          }
          if(this.title == '新增收货信息'){
            this.addAddress()
          }else{
            this.updateAddress()
          }
        } else {
          return false;
        }
      });
    },
    //滚动切换地址
    handleScrollPage(dir) {
      if(dir == 'next'){
        if(this.scrollPage>=this.scrollMaxPage-1){
          return;
        }
        this.scrollPage ++;
        this.scrollWidth = - this.scrollPage * 1110 +'px'
      }else{
        if(this.scrollPage<=0){
          return;
        }
        this.scrollPage --;
        this.scrollWidth = - this.scrollPage * 1110 +'px'
      }
    },
    //选中地址
    handleSelectAddress(index) {
      this.addressActive = index;
      this.addressInfo = this.addressList[index];
      this.getSettleAmount();
    },
    //移除商品
    handleRemove() {
      this.removeProdcut()
    },
    removeProdcut() {
      let tempMap = {};
      this.abnormalList.forEach((item) => {
        tempMap[item.productSpecificationId] = true;
      })
      this.orderList = this.orderList.filter((item) => {
        item.cartItemDTOList = item.cartItemDTOList.filter((listItem)=>{
          return !tempMap[listItem.productSpecificationId]
        })
        return item.cartItemDTOList.length
      })
      this.getSettleAmount()

      if(!this.orderList.length){
        location.href = this.URL.mall + '/cart/list'
        // this.$router.push({
        //   name: 'CartList'
        // })
      }
      this.dialogAbnormal = false;
    },
    handleBack() {
      location.href = this.URL.mall + '/cart/list'
      // this.$router.push({
      //   name: 'CartList'
      // })
      this.dialogAbnormal = false;
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/pages/confirmOrder.scss';
</style>
<style lang="scss">
  .form-dialog-address{
    .el-form-item__content{
      margin-right: 21px;
    }
    .checkbox{
      margin-left: 130px;
    }
    .area-select-wrap .area-select{
      margin-left: 0;
      margin-right: 2px;
      &:last-child{
        margin-right: 0;
      }
    }
  }
  .i-space{
    margin: 0 15px;
  }
</style>
